package lbframework.classe;

import java.io.File;
import java.io.FileInputStream;
import java.util.Vector;
import lbframework.remote.Arquivo;

public class Properties {

    private java.util.Properties oPropertie = null;
    private String arquivo = null;

    public Properties(String i_arquivo) throws Exception {
        arquivo = i_arquivo;
        FileInputStream input = new FileInputStream(new File(i_arquivo));

        oPropertie = new java.util.Properties();
        oPropertie.load(input);

        input.close();
    }

    private String getPropertie(String i_key) throws Exception {
        String value = oPropertie.getProperty(i_key);

        if (value == null) {
            return "";
        } else {
            return value.trim();
        }
    }

    public void setPropertie(String i_key, String i_value) throws Exception {
        Vector<String> vLine = new Vector();
        Arquivo arqProperties = null;

        boolean achou = false;

        try {
            arqProperties = new Arquivo(arquivo, "r");

            while (arqProperties.ready()) {
                String line = arqProperties.readLine();

                if (!line.startsWith(i_key)) {
                    vLine.add(line);
                } else {
                    vLine.add(i_key + " = " + i_value);
                    achou = true;
                }
            }

            if (!achou) {
                vLine.add(i_key + " = " + i_value);
            }

        } catch (Exception ex) {
        } finally {
            try {
                arqProperties.close();

            } catch (Exception ex) {
            }
        }

        try {
            arqProperties = new Arquivo(arquivo, "w");

            for (String line : vLine) {
                arqProperties.write(line);
            }

        } catch (Exception ex) {
        } finally {
            try {
                arqProperties.close();

            } catch (Exception ex) {
            }
        }
    }

    public String getString(String i_key) throws Exception {
        return getPropertie(i_key);
    }

    public int getInt(String i_key) throws Exception {
        String value = getPropertie(i_key);

        if (value.equals("")) {
            return 0;
        } else {
            return Integer.parseInt(getPropertie(i_key));
        }
    }

    public long getLong(String i_key) throws Exception {
        String value = getPropertie(i_key);

        if (value.equals("")) {
            return 0;
        } else {
            return Long.parseLong(getPropertie(i_key));
        }
    }

    public boolean getBoolean(String i_key) throws Exception {
        String value = getPropertie(i_key);

        if (value.equals("")) {
            return false;
        } else {
            return Boolean.parseBoolean(getPropertie(i_key));
        }
    }
}
